home *** CD-ROM | disk | FTP | other *** search
/ Collection of Tools & Utilities / Collection of Tools and Utilities.iso / c / jpl_c.zip / UTOA.C < prev   
Text File  |  1988-08-06  |  2KB  |  63 lines

  1. /* 1.1  01-08-86                         (utoa.c)
  2.  ************************************************************************
  3.  *            Robert C. Tausworthe                *
  4.  *            Jet Propulsion Laboratory            *
  5.  *            Pasadena, CA 91009        1984        *
  6.  ************************************************************************
  7.  *
  8.  *    These functions are modified versions of itoa() found in Kernighan
  9.  *    and Ritchie, page 60, with modifications as suggested in exercises
  10.  *    3-4 and 3-5, and with returned pointer to result string.
  11.  *
  12.  *----------------------------------------------------------------------*/
  13.  
  14. #include "defs.h"
  15. #include "stdtyp.h"
  16. #include "errno.h"
  17.  
  18. /************************************************************************/
  19.     STRING
  20. utoa(s, n, w)        /* return pointer to string s, which contains ascii
  21.                value of unsigned n, base 10, min width w.    */
  22. /*----------------------------------------------------------------------*/
  23. STRING s;
  24. unsigned n;
  25. {
  26.     STRING utoab();
  27.  
  28.     return utoab(s, n, w, 10);
  29. }
  30.  
  31. /************************************************************************/
  32.     STRING
  33. utoab(s, n, w, b)    /* convert n to a minimum of w ascii characters,
  34.                base b, and put  in s.  Return pointer to s.    */
  35. /*----------------------------------------------------------------------*/
  36. STRING s;
  37. unsigned n;
  38. {
  39.     LOCAL char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
  40.     int i, j;
  41.     char c, fill;
  42.  
  43.     if (w < 0)
  44.     {    fill = '0';
  45.         w = -w;
  46.     }
  47.     else
  48.         fill = ' ';
  49.     i = 0;
  50.     do            /* generate digits in reverse order:    */
  51.     {    s[i++] = digits[n % b];
  52.     } while (n /= b);
  53.     while (i < w)            /* expand to proper width.    */
  54.         s[i++] = fill;    /* i is just beyond last filled postion    */
  55.     s[i--] = NULL;            /* add null terminator    */
  56.     for (i, j = 0; j < i; j++, i--) /*  now reverse chars */
  57.     {    c = s[j];
  58.         s[j] = s[i];
  59.         s[i] = c;
  60.     }
  61.     return s;
  62. }
  63.